const { setAbstractDataList } = require('./data');
const { KEYWORD } = require('./keyword');
const { createXlsxFile } = require('../../utils/fileUtil');

/** 摘要数据处理
 * 先实现每次请求一篇数据，然后获取文章内容
 */
async function abstractHandler(id, abstractRes) {
  const abstractTextArray = abstractRes.data
    ?.match(new RegExp(`<AbstractText.*?>([\\s\\S]*?)</AbstractText>`, 'gi'))
    ?.map((item) => {
      const label = item.match(/Label="([^"]*)"/i)?.at(-1);
      const content = item.replace(/<[^>]+>/g, '');
      return label ? `${label}: ${content}` : content;
    });
  const abstractData = { pmid: id, abstract: abstractTextArray?.join('\n') };
  console.log('--abstractData--', abstractData);
  setAbstractDataList(abstractData);
}

function splitChunk(chunks, size) {
  return Array.from({ length: Math.ceil(chunks.length / size) }, (_, i) => chunks.slice(i * size, i * size + size));
}

function getXlsxData(data) {
  const columns = [
    { name: 'PMID', key: 'pmid', width: '30' },
    { name: 'ABSTRACT', key: 'abstract', width: '90' },
  ];
  const outputName = `${KEYWORD}-${new Date().getTime()}.csv`;
  const outputPath = 'C://Users//Public';
  const titleList = ['PMID', 'ABSTRACT'];
  createXlsxFile(data, columns, outputName, outputPath, titleList);
}

module.exports = { abstractHandler, getXlsxData, splitChunk };
